package DAO;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import com.mysql.jdbc.Driver;

public class JDBCConnect {

	//获取数据库连接
	public static Connection getConnection() throws SQLException{
		return getConnection("servletdb","root","");
	}

	private static Connection getConnection(String dbName, String user, String password) throws SQLException {
		// TODO Auto-generated method stub
		String url = "jdbc:mysql://localhost:3306/"+dbName+
				"?characterEncoding=utf-8";
		//连接mysql "com.mysql.Driver"
		DriverManager.registerDriver(new Driver());
		return DriverManager.getConnection(url, user, password);
	}
	
	//设置PreparedStatement参数
	public static void setParams(PreparedStatement preStat,Object...params) throws SQLException{
		if(params == null || params.length == 0){
			return ;
		}
		for(int i = 1;i<=params.length;i++){
			Object param = params[i-1];
			if(param == null){
				preStat.setNull(i, Types.NULL);
			}else if(param instanceof Integer){
				preStat.setInt(i, (Integer)param);
			}else if(param instanceof String){
				preStat.setString(i, (String)param);
			}else if(param instanceof Double){
				preStat.setDouble(i, (Double)param);
			}else if(param instanceof Long){
				preStat.setLong(i, (Long)param);
			}else if (param instanceof Timestamp) {
				preStat.setTimestamp(i, (Timestamp)param);
			}else if(param instanceof Boolean){
				preStat.setBoolean(i, (Boolean)param);
			}else if(param instanceof Date){
				preStat.setDate(i, (Date)param);
			}
		}
	}
	//执行sql 
	public static int executeUpdate(String sql) throws SQLException{
		return executeUpdate(sql,new Object[]{});
	}

	public static int executeUpdate(String sql, Object...params) throws SQLException {
		// TODO Auto-generated method stub
		Connection conn = null;
		PreparedStatement preStat = null;
		try {
			conn = getConnection();
			preStat = conn.prepareStatement(sql);
			setParams(preStat, params);
			return preStat.executeUpdate();
		} finally {
			// TODO: handle exception
			if(preStat != null){
				preStat.cancel();
			}
			if(conn!=null){
				conn.close();
			}
		}
	}
	
}
